<template>
  <div style="background: #ebe8eb">
    <Head />
    <div class="goods-detail">
      <div class="goods-detail-show">
        <div class="spec-preview">
          <img :src="imageUrl" alt="" />
          <div class="event" @mousemove="handler"></div>
          <div class="big">
            <img
              src="https://gw.alicdn.com/imgextra/i2/2211583245773/O1CN01FjjB8b1sW5Oh4EZM3_!!2211583245773.jpg_110x10000Q75.jpg_.webp"
              alt=""
              ref="big"
            />
            <img :src="bigImg" alt="" ref="big" />
          </div>
          <!-- 遮罩层 -->
          <div class="mask" ref="mask"></div>

          <ul class="spec-scroll">
            <li @click="changeImg(item)" v-for="item in imgList">
              <img :src="item.url" />
            </li>
            <!-- <li><img src="../assets/goods2.jpeg" /></li>
            <li><img src="../assets/goods1.jpeg" /></li> -->
          </ul>
        </div>

        <div class="info">
          <div class="goods-title">
            {{ goodsDetail.goodsName }}
          </div>
          <div class="goods-money-box">
            <div class="goods-money">热卖促销¥{{ goodsDetail.price }}</div>
            <div
              :style="{ color: isWish ? 'red' : '#969696' }"
              class="goods-star-box"
              @click="handlerStar(goodsDetail)"
            >
              <el-icon
                class="goods-star"
                :style="{ color: isWish ? 'red' : '#969696' }"
              >
                <Star />
              </el-icon>
              <span style="margin-left: 4px">
                {{ isWish ? '已收藏' : '收藏' }}
              </span>
            </div>
          </div>
          <div class="goods-num">库存：{{ goodsDetail.goodsNum }}</div>
          <div class="goods-num">
            发货地：{{ goodsDetail.address }} 配送至：
            <el-icon
              color="#2e92fa"
              style="cursor: pointer; margin-right: 6px"
              @click="dialogVisible = true"
            >
              <Location />
            </el-icon>
            <el-select
              v-model="defAdder"
              placeholder="请选择配送地址"
              style="width: 200px"
            >
              <el-option
                :label="address.address"
                :value="address.id"
                v-for="address in addressList"
              ></el-option>
            </el-select>
          </div>

          <div class="goods-num">
            <div style="flex-basis: 80px">类别：</div>
            <el-radio-group
              v-model="category"
              style="max-height: 124px; overflow: auto"
            >
              <el-radio :label="item.key" border v-for="item in goodsType">
                {{ item.value }}
              </el-radio>
            </el-radio-group>
          </div>

          <div class="goods-num">
            <div style="margin-right: 10px">数量：</div>
            <el-input-number
              v-model="num"
              :min="1"
              :max="10"
              label="描述文字"
            ></el-input-number>
          </div>
          <div class="goods-btn">
            <el-button type="primary" class="goods-btn-buy" @click="addOrder">
              立即购买
            </el-button>
            <el-button type="primary" class="goods-btn-cart" @click="pushCart">
              加入购物车
            </el-button>
          </div>
        </div>
      </div>

      <el-tabs v-model="activeName" class="tabs">
        <el-tab-pane label="商品详情" name="first">
          <el-descriptions size="large" column="3" title="">
            <el-descriptions-item
              v-for="(item, index) in goodsInfo"
              :label="item.key"
            >
              {{ item.value }}
            </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        <el-tab-pane label="宝贝评价" name="t">
          <div class="comment" v-for="(item, i) in contentReplyList">
            <div class="user-info">
              <div class="user-img">
                <img v-if="item.userImg" :src="origin + item.userImg" alt="" />
                <img v-else src="../assets/user.png" alt="" />
              </div>
              <div>
                <div class="user-name">{{ item.userName }}</div>
                <div class="user-time">{{ item.contentTime }}</div>
              </div>
            </div>
            <div class="comment-text">{{ item.content }}</div>
            <div class="comment-imgs">
              <img
                v-for="img in item.images"
                :src="origin + img.url"
                alt=""
                style="margin-right: 4px"
              />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>

      <el-dialog title="" v-model="dialogVisible" width="400px" center>
        <div>
          <area-picker
            ref="picker"
            v-model="area"
            :columns="3"
            @pick="handlePick"
          />
        </div>
      </el-dialog>
    </div>

    <div class="contact-service-btn" @click="isOpenContact = true">
      联系
      <br />
      客服
    </div>

    <div class="contact-service" v-if="isOpenContact">
      <div class="contact-service-head">
        <div class="contact-service-title">联系客服</div>
        <div class="contact-service-close" @click="isOpenContact = false">
          <el-icon><Close /></el-icon>
        </div>
      </div>
      <div class="contact-service-content" ref="targetBox">
        <div v-for="item in messageList" style="margin: 8px 0">
          <div v-if="item.type === 'send'" class="content-right">
            <div class="send-name">{{ item.name }} {{ item.date }}</div>
            <div class="send-text">{{ item.value }}</div>
          </div>
          <div v-if="item.type === 'accept'" class="content-left">
            <div class="accept-name">{{ item.name }} {{ item.date }}</div>
            <div class="accept-text">{{ item.value }}</div>
          </div>
        </div>
      </div>
      <div class="contact-service-footer">
        <el-input
          v-model="textarea"
          :rows="2"
          type="textarea"
          placeholder="开始对话吧～"
          @keyup.enter.prevent="handleEnterKey"
        />
        <el-button type="primary" class="send-btn" @click="handleEnterKey">
          <el-icon><Position /></el-icon>
        </el-button>
      </div>
    </div>
    <Footer></Footer>
  </div>
</template>

<script>
import Head from '../components/Head.vue'
import Footer from '../components/Footer.vue'
import areaPicker from '../components/areaPicker/index.vue'
import dayjs from 'dayjs'
import {
  getContent,
  createContent,
  getGoodsContentReplyList,
  getContentReply
} from '../api/content.js'
import {
  getGoodsDetail,
  wishGoods,
  getWishGoodsFlag,
  cancelWishGoods
} from '../api/goods.js'
import { adderList } from '../api/address.js'
import {
  getShopCart,
  deleteShopCart,
  createShopCart,
  clearShopCart
} from '../api/shopCar.js'
import { createOrder } from '../api/order.js'
import { userList, updateUser, deleteUser } from '../api/user'

export default {
  components: {
    areaPicker
  },
  data() {
    return {
      defAdder: '',
      addressList: [],
      userInfo: JSON.parse(localStorage.getItem('user_info')),
      goodsDetail: {},
      path: `ws://43.136.166.102:8090/websocket/${
        JSON.parse(localStorage.getItem('user_info')).role
      }`,
      socket: '',
      textarea: '',
      isOpenContact: false,
      dialogVisible: false,
      activeName: 'first',
      num: 1,
      category: '',
      goodsInfo: [
        { key: '品牌', value: 'JOYZONE/久生' },
        { key: '品名', value: '久生幼猫粮' },
        { key: '包装种类', value: '袋装' },
        { key: '食品口味：幼猫', value: '果寡糖 硫酸软骨素' },
        { key: '生产厂家名称', value: '山东汉欧生物科技有限公司' },
        { key: '生产许可证号/进口登记证号', value: '鲁饲证（2018）16015' },
        { key: '适用阶段', value: '全阶段' },
        { key: '是否进口', value: '否' },
        { key: '规格类型', value: '正常规格' },
        { key: '净含量', value: '10kg' },
        { key: '储存条件', value: '常温' },
        { key: '保质期', value: '18个月' }
      ],
      goodsType: [],
      messageList: [
        {
          name: '',
          value: '欢迎您光临本店',
          date: dayjs(new Date().toLocaleString()).format('HH:mm:ss'),
          type: 'accept'
        }
      ],
      imgList: [],
      imageUrl: '',
      bigImg: '',
      isWish: false,
      contentReplyList: [],
      origin: 'http://43.136.166.102:8090',
      users: []
    }
  },
  created() {
    console.log(this.$route.params.id)
  },
  mounted() {
    const goodsId = this.$route.params.id
    getGoodsDetail(goodsId).then((res) => {
      this.goodsDetail = res
      this.imageUrl = res.images[0].url.includes('http')
        ? res.images[0].url
        : this.origin + res.images[0].url
      this.imgList = res.images.map((item) => {
        return {
          ...item,
          url: item.url.includes('http') ? item.url : this.origin + item.url
        }
      })
      this.category = res.normsDtos[0].id

      this.goodsType = res.normsDtos.map((item) => {
        return { key: item.id, value: item.title }
      })
      this.bigImg = res.images[0].url
    })
    // 根据商品ID获取商品数据，并进行相应的处理
    this.init()
    adderList(this.userInfo.id).then((res) => {
      this.addressList = res
      this.defAdder = res.filter((item) => item.isDef === 1)

      // this.defAdder = this.defAdder ? this.defAdder[0].id : res[0].id
      this.defAdder = res[0].id
    })
    userList({ pageNum: 1, pageSize: 100 }).then((res) => {
      this.users = res.records
      console.log('---', this.users)
    })

    getGoodsContentReplyList(goodsId).then((res) => {
      this.contentReplyList = res.map((item) => {
        return {
          ...item,
          contentTime: dayjs(item.contentTime).format('YYYY-MM-DD HH:mm:ss'),
          userImg: this.users.find((user) => item.userId === user.id)?.imageUrl
        }
      })
    })
    this.getWish()
  },
  methods: {
    getWish() {
      getWishGoodsFlag({
        goodsId: this.$route.params.id,
        userId: this.userInfo.id
      }).then((res) => {
        this.isWish = res === 0 ? false : true
      })
    },
    pushCart() {
      createShopCart({
        goodsId: this.$route.params.id,
        buyNum: this.num,
        userId: this.userInfo.id,
        goodsName: this.goodsDetail.goodsName,
        goodsImg: this.goodsDetail.goodsImg,
        totalPrice: this.goodsDetail.price * this.num
      }).then((res) => {
        ElMessage.success('已加入购物车！')
      })
    },
    addOrder() {
      createOrder({
        goodsId: this.$route.params.id,
        orderNum: this.num,
        userId: this.userInfo.id,
        goodsName: this.goodsDetail.goodsName,
        addressId: this.defAdder,
        status: '1',
        totalPrice: this.goodsDetail.price * this.num
      }).then((res) => {
        ElMessage.success('已生成订单！')
      })
    },
    changeImg(img) {
      this.imageUrl = img.url

      this.bigImg = img.url
    },
    handler(event) {
      let mask = this.$refs.mask
      let bigImg = this.$refs.big
      // 遮罩层可移动的范围：鼠标的当前坐标到该元素的距离（左侧、顶部）减去 遮罩层宽、高的一半(遮罩层是一个以鼠标为中心的正方形)
      let left = event.offsetX - mask.offsetWidth / 2
      let top = event.offsetY - mask.offsetHeight / 2

      // 约束遮罩层可移动的范围
      if (left <= 0) left = 0
      if (left >= mask.offsetWidth) left = mask.offsetWidth
      if (top <= 0) top = 0
      if (top >= mask.offsetHeight) top = mask.offsetHeight

      // 修改元素的left|top属性值
      mask.style.left = left + 'px'
      mask.style.top = top + 'px'
      bigImg.style.left = -2 * left + 'px'
      bigImg.style.top = -2 * top + 'px'
    },
    handlePick(areaList) {
      console.log(areaList)
    },
    handleEnterKey(e) {
      if (e.preventDefault) e.preventDefault()
      this.messageList.push({
        name: this.userInfo.userName,
        type: 'send',
        value: this.textarea,
        date: dayjs(new Date().toLocaleString()).format('HH:mm:ss')
      })
      this.send(this.textarea)
      this.textarea = ''
      this.scrollIntoView()
    },
    scrollIntoView() {
      this.$nextTick(() => {
        // 确保DOM已经更新完成
        const targetBox = this.$refs.targetBox
        targetBox.scrollTop = targetBox.scrollHeight
        if (targetBox) {
          // targetBox.scrollIntoView({ behavior: 'smooth', block: 'end' })
        }
      })
    },
    init: function () {
      if (typeof WebSocket === 'undefined') {
        alert('您的浏览器不支持socket')
      } else {
        // 实例化socket
        this.socket = new WebSocket(this.path)
        // 监听socket连接
        this.socket.onopen = this.open
        // 监听socket错误信息
        this.socket.onerror = this.error
        // 监听socket消息
        this.socket.onmessage = this.getMessage
      }
    },
    open: function () {
      console.log('socket连接成功')
    },
    error: function () {
      console.log('连接错误')
    },
    getMessage: function (msg) {
      if (JSON.parse(msg.data).msg) {
        this.messageList.push({
          name: '',
          value: JSON.parse(msg.data).msg,
          date: dayjs(new Date().toLocaleString()).format('HH:mm:ss'),
          type: 'accept'
        })
      }
      this.scrollIntoView()

      console.log(msg.data)
    },
    // 发送消息给被连接的服务端
    send: function (params) {
      this.socket.send(params)
    },
    close: function () {
      console.log('socket已经关闭')
    },

    handlerStar(item) {
      if (this.isWish) {
        cancelWishGoods({ goodsId: item.id, userId: this.userInfo.id }).then(
          () => {
            this.$message.success('取消收藏成功')
            this.getWish()
          }
        )
      } else {
        wishGoods({ goodsId: item.id, userId: this.userInfo.id }).then(() => {
          this.$message.success('收藏成功')
          this.getWish()
        })
      }
    }
  },
  created() {},
  destroyed() {
    // 销毁监听
    this.socket.onclose = this.close
  }
}
</script>

<style lang="less" scoped>
.goods-detail {
  width: 1100px;
  margin: 20px auto;
  padding: 20px;
  border-radius: 20px;
  background: #fff;

  .goods-detail-show {
    display: flex;
  }

  .info {
    position: relative;
  }

  .goods-title {
    line-height: 28px;
    color: #000;
    letter-spacing: 0;
    font-size: 20px;
    font-family: PingFang SC;
    font-weight: 900;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }

  .goods-money-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .goods-money {
    color: rgb(255, 79, 0);
    font-size: 28px;
    line-height: 28px;
    font-family: AlibabaSans102-Bold;
    font-weight: bold;
    margin-top: 10px;
  }

  .goods-star {
    cursor: pointer;
    font-size: 16px;
  }

  .goods-star-box {
    font-size: 12px;
    display: flex;
    align-items: center;
    cursor: pointer;
  }

  .goods-star:hover {
    color: #f30213;
  }

  .goods-btn {
    position: absolute;
    bottom: 0;
    .el-button--primary {
      border: transparent;
      border-radius: 36px;
      padding: 20px 30px;
    }
    &-cart {
      background: linear-gradient(90deg, rgb(255, 203, 0), rgb(255, 148, 2));
      box-shadow: rgba(255, 203, 0, 0.2) 0px 9px 13px 0px;
      vertical-align: top;
    }
    &-buy {
      background: linear-gradient(90deg, rgb(255, 119, 0), rgb(255, 73, 0));
      box-shadow: rgba(255, 119, 0, 0.2) 0px 9px 13px 0px;
      vertical-align: top;
    }
  }
  .goods-num {
    display: flex;
    font-family: PingFangSC-Regular;
    font-size: 14px;
    color: #7f7f7f;
    line-height: 14px;
    margin-top: 21px;
    align-items: center;
    max-width: 80%;
    // flex-wrap: wrap;
  }

  .spec-preview {
    position: relative;
    width: 400px;
    height: 400px;
    border: 1px solid #ccc;
    margin-right: 20px;
    img {
      width: 100%;
      height: 100%;
    }
    .event {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 998;
    }

    .mask {
      width: 50%;
      height: 50%;
      background-color: rgba(255, 0, 0, 0.3);
      position: absolute;
      left: 0;
      top: 0;
      display: none;
    }

    .big {
      width: 100%;
      height: 100%;
      position: absolute;
      top: -1px;
      left: 100%;
      border: 1px solid #aaa;
      overflow: hidden;
      z-index: 998;
      display: none;
      background: white;
      img {
        width: 200%;
        max-width: 200%;
        height: 200%;
        position: absolute;
        left: 0;
        top: 0;
      }
    }
    .event:hover ~ .mask,
    .event:hover ~ .big {
      display: block;
    }
    .spec-scroll {
      display: flex;
      list-style-type: none;
      overflow: auto;
      li {
        margin-right: 10px;
        cursor: pointer;
        img {
          width: 50px;
        }
      }
    }
  }
}

.tabs {
  margin: 30px 0;
  margin-top: 80px;
  .comment {
    margin-bottom: 30px;
    border-bottom: 1px solid #f4f4f4;
    padding-bottom: 30px;
  }

  .user-info {
    display: flex;
    align-items: center;
    .user-name {
      font-family: PingFang SC;
      font-weight: 700;
      font-size: 17px;
      color: #000;
      line-height: 22px;
    }
    .user-time {
      font-family: PingFang SC;
      font-size: 14px;
      color: #7a7a7a;
      line-height: 18px;
    }
  }

  .user-img {
    margin-right: 10px;
    img {
      width: 36px;
      height: 36px;
      border-radius: 50%;
    }
  }

  .comment-text {
    margin-top: 15px;
    font-family: PingFang SC;
    font-size: 16px;
    color: #000;
    line-height: 22px;
  }

  .comment-imgs {
    display: flex;
    height: 100px;
    width: 100px;
    margin-right: 4px;
    margin-top: 15px;
    cursor: pointer;
    img {
      width: 100px;
      height: 100px;
      margin-right: 8px;
    }
  }
}

.contact-service-btn {
  width: 54px;
  height: 54px;
  border-radius: 50%;
  font-weight: 600;
  font-size: 13px;
  color: #fff;
  line-height: 22px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  position: fixed;
  right: 80px;
  top: 200px;
  background: linear-gradient(to right, #ff0000, #fc7544);
  box-shadow: 0px 4px 10px 0px rgba(255, 102, 102, 0.3);
}

.contact-service {
  right: 80px;
  top: 50px;
  width: 400px;
  height: 80vh;
  position: fixed;
  background: #fff;
  z-index: 99;
  box-shadow: 0px 12px 32px 4px rgba(0, 0, 0, 0.04),
    0px 8px 20px rgba(0, 0, 0, 0.08);
  border-radius: 16px;
  &-head {
    text-align: center;
    padding: 10px;
    border-bottom: 1px solid #e4e7ed;
  }
  &-content {
  }
  &-footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 50px;
    border-top: 1px solid #e4e7ed;
    left: 0;
    .el-textarea__inner {
      box-shadow: 0 0 0 0 #fff !important;
    }

    .send-btn {
      position: absolute;
      top: 10px;
      right: 10px;
    }
  }
  &-close {
    position: absolute;
    top: 12px;
    right: 14px;
    cursor: pointer;
  }

  &-content {
    height: calc(80vh - 100px);
    padding: 8px;
    overflow-y: scroll;
    background: rgb(253, 245, 234, 0.1);
    .content-right {
      display: flex;
      flex-direction: column;
      align-items: end;
      .send-name {
        font-size: 12px;
      }

      .send-text {
        max-width: 40%;
        margin-left: auto;
        padding: 10px;
        color: #fff;
        color: #273849;
        font-size: 15px;
        background-color: #d2e0ff;
        border: 1px solid rgba(255, 255, 255, 0.45);
        border-radius: 10px;
        border-radius: 8px 0 8px 8px;
      }
    }
    .content-left {
      .accept-name {
        font-size: 12px;
      }
      .accept-text {
        max-width: 60%;
        padding: 10px;
        font-size: 15px;
        background: #fff;
        border: 1px solid #fff;
        border-radius: 0 8px 8px;
      }
    }
  }
}

.el-radio.is-bordered {
  margin-bottom: 6px;
}
</style>
<style>
.el-textarea__inner {
  box-shadow: 0 0 0 0 #fff !important;
}
</style>
